﻿using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Print.Domain;
using Mengsk.ProxyDelivery.Print.ViewModels;
using Mengsk.ProxyDelivery.Service;
using Mengsk.ProxyDelivery.Utls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Printing;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.Print.UI
{
    /// <summary>
    /// Interaction logic for PrintUserControl.xaml
    /// </summary>
    public partial class PrintUserControl : UserControl
    {
        public static readonly DependencyProperty DeliveryPrintTemplatesProperty = DependencyProperty.Register("DeliveryPrintTemplates", typeof(ObservableCollection<PrintTemplate>), typeof(PrintUserControl));

        private OrderService orderRepertory = ServiceContainer.GetService<OrderService>();

        public System.Collections.ObjectModel.ObservableCollection<PrintTemplate> DeliveryPrintTemplates { get { return (ObservableCollection<PrintTemplate>)this.GetValue(DeliveryPrintTemplatesProperty); } set { this.SetValue(DeliveryPrintTemplatesProperty, value); } }

        public PrintUserControl()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (DeliveryPrintTemplates == null)
                {
                    DeliveryPrintTemplates = new System.Collections.ObjectModel.ObservableCollection<PrintTemplate>();
                }
                DeliveryPrintTemplates.Clear();
                foreach (var item in new FilePrintTemplateRepertory().GetAll())
                {
                    DeliveryPrintTemplates.Add(item);
                }
                this.dpEnd.Value = DateTime.Now;
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载出错:" + ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }

        private void btnDownloadOrder_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int sellerId = 0;
                DateTime dt = this.dpEnd.Value == null ? this.orderRepertory.GetDBMinTime() : this.dpEnd.Value.Value;
                int.TryParse(this.tbSellerId.Text.Trim(), out sellerId);
                Order[] orders = this.orderRepertory.GetByAll(sellerId, "", "", "", "", "", "", "", (int)OrderState.Payed, 0, 0, -1, 0, DateTime.Now.AddDays(-30), dt, 0, 0).Datas.ToArray();
                var groups = orders.GroupBy(new Func<Order, long>(obj => obj.DeliveryTemplateId));
                var viewModels = groups.Select(obj => new ViewModels.PrintOrderPageViewModel(obj.ToArray())).ToArray();
                DeliveryTemplateService deliveryTemplateRepertory = ServiceContainer.GetService<DeliveryTemplateService>();
                foreach (var vm in viewModels)
                {
                    var deliveryTemplate = deliveryTemplateRepertory.GetById(vm.OrderViewModels[0].Source.DeliveryTemplateId);
                    if (deliveryTemplate == null)
                    {
                        vm.DeliveryTemplateName = "运费模板不存在";
                    }
                    else
                    {
                        vm.DeliveryTemplateName = deliveryTemplate.Name;
                    }
                }
                this.tcOrderPages.ItemsSource = viewModels;
                if (viewModels.Count() > 0)
                {
                    this.tcOrderPages.SelectedIndex = 0;
                }
                else
                {
                    MessageBox.Show("没有需要打印的订单");
                }
                this.tbTotalCount.Text = "当前订单总数: " + orders.Length;
            }
            catch (Exception ex)
            {
                MessageBox.Show("下载订单出错:" + ex.Message + ex.GetType().FullName);
                MessageBox.Show(ex.StackTrace);
            }
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                if (btn == null)
                {
                    return;
                }

                PrintOrderPageViewModel orderPage = btn.DataContext as PrintOrderPageViewModel;
                if (orderPage == null)
                {
                    return;
                }

                if (orderPage.Starting == null)
                {
                    orderPage.Starting += new EventHandler(OnStarting_Handler);
                    orderPage.Ended += new EventHandler(OnEnded_Handler);
                }

                if (orderPage.IsPrinting)
                {
                    if (MessageBox.Show("是否要停止", "警告", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
                    {
                        return;
                    }
                    orderPage.Stop();
                    return;
                }

                Grid grid = btn.Parent as Grid;
                ComboBox cmb = grid.FindName("cbbDeliveryTemplates") as ComboBox;
                TextBox tb = grid.FindName("tbDeliveryNumber") as TextBox;
                PrintTemplate temp = cmb.SelectedItem as PrintTemplate;
                DataGrid dg = grid.FindName("dgOrders") as DataGrid;

                var selectedOrders = orderPage.OrderViewModels.Where(obj => obj.IsChecked).ToArray();
                if (selectedOrders.Count() < 1)
                {
                    throw new Exception("没有需要打印的数据");
                }

                if (dg == null)
                {
                    throw new Exception("无法找到名称为:dgOrders的DatGrid对象");
                }

                DataGridColumn goodsCol = dg.Columns.FirstOrDefault(col => col.Header.ToString() == "门牌编号");
                string deliveryNumber = tb.Text.Trim();

                if (temp == null)
                {
                    MessageBox.Show("请选择相应的快递模板");
                    return;
                }

                if (string.IsNullOrWhiteSpace(deliveryNumber) && temp.PaperType != PaperType.HOT)
                {
                    MessageBox.Show("非电子面单起始运单号不能为空");
                    return;
                }

                if (goodsCol == null)
                {
                    throw new Exception("无法找到列标题为:商品信息的列");
                }

                //检查快递模板
                if (orderPage.DeliveryTemplateName != "运费模板不存在" && PrintTemplateCompanyHelper.GetDeliveryCompanyKeyword(temp.DeliveryCompany.DeliveryCompany).Equals(PrintTemplateCompanyHelper.GetDeliveryCompanyKeyword(orderPage.DeliveryTemplateName)) == false)
                {
                    MessageBox.Show("打印模板与当前快递公司不一致", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                //检查货到付款
                if (orderPage.DeliveryTemplateName.Contains("货到") && temp.Name.Contains("货到") == false)
                {
                    MessageBox.Show("打印模板与当前快递公司不一致", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                string printer = LocalConfigService.GetValue(temp.PaperType == PaperType.HOT ? "HotPrinter" : "DeliveryPrinter", "");
                if (string.IsNullOrWhiteSpace(printer))
                {
                    throw new Exception("系统中没有配置快递单打印机");
                }
                string popMessage = string.Format("{0}打印模板:{1}{2}打印设备:{3}{4}打印数据:{5}", Environment.NewLine, temp.Name, Environment.NewLine, printer, Environment.NewLine, selectedOrders.Count());
                if (MessageBox.Show(popMessage, "确认打印", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
                {
                    return;
                }
                PrintDialog pd = PrintUtil.GetPrinter(printer);
                var ca = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket);
                pd.PrintTicket.PageBorderless = PageBorderless.Borderless;
                pd.PrintTicket.PageOrientation = PageOrientation.Portrait;
                pd.PrintTicket.PagesPerSheetDirection = PagesPerSheetDirection.LeftBottom;

                //自动安照商品信息排序
                goodsCol.SortDirection = null;
                this.SortData(dg, goodsCol);
                var number = orderPage.Print(pd, temp, deliveryNumber);
                LocalConfigService.UpdateValue(temp.Name, number);
                tb.Text = number;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void OnStarting_Handler(object sender, EventArgs e)
        {
        }

        private void OnEnded_Handler(object sender, EventArgs e)
        {
        }

        private void chkSelectAll_Checked(object sender, RoutedEventArgs e)
        {
            this.UpdateCheck(sender);
        }

        private void chkSelectAll_Unchecked(object sender, RoutedEventArgs e)
        {
            this.UpdateCheck(sender);
        }

        private void UpdateCheck(object sender)
        {
            try
            {
                CheckBox cb = sender as CheckBox;
                if (cb == null)
                {
                    return;
                }

                var item = cb.DataContext as PrintOrderPageViewModel;
                if (item == null)
                {
                    return;
                }

                foreach (var i in item.OrderViewModels)
                {
                    i.IsChecked = false;
                }

                if (item.InputCount <= 0)
                {
                    foreach (var i in item.OrderViewModels)
                    {
                        i.IsChecked = cb.IsChecked.Value;
                    }
                }
                else
                {
                    for (int i = 0; i < item.InputCount && i < item.OrderViewModels.Count; i++)
                    {
                        item.OrderViewModels[i].IsChecked = cb.IsChecked.Value;
                    }
                }

                Debug.WriteLine(cb.GetHashCode());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "全选或者不选处理失败");
            }
        }

        private void DataGrid_Sorting(object sender, DataGridSortingEventArgs e)
        {
            try
            {
                this.SortData(sender as DataGrid, e.Column);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "排序失败");
            }
            finally
            {
                e.Handled = true;
            }

        }

        private void SortData(DataGrid dg, DataGridColumn col)
        {
            if (dg == null)
            {
                MessageBox.Show("事件源不是DataGrid无法排序");
                return;
            }
            string sortPath = col.SortMemberPath;
            if (string.IsNullOrWhiteSpace(sortPath))
            {
                MessageBox.Show("排序字段为空", "排序失败");
                return;
            }
            var pageVM = dg.DataContext as PrintOrderPageViewModel;
            if (pageVM == null)
            {
                MessageBox.Show("DataGrid的DataContext不是PrintOrderPageViewModel或者数据源为空");
                return;
            }
            var sortType = col.SortDirection == null ? ListSortDirection.Ascending : (col.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending);
            var vms = pageVM.OrderViewModels;
            List<PrintOrderViewModel> newVms = null;
            if (sortPath.Contains("PopType"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Source.PopType).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Source.PopType).ToList();
                }
            }
            else if (sortPath.Contains("Id"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Source.Id).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Source.Id).ToList();
                }
            }
            else if (sortPath.Contains("SellerId"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Source.SellerId).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Source.SellerId).ToList();
                }
            }
            else if (sortPath.Contains("PopBuyerId"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Source.PopBuyerId).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Source.PopBuyerId).ToList();
                }
            }
            else if (sortPath.Contains("PayTime"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Source.PayTime).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Source.PayTime).ToList();
                }
            }
            else if (sortPath.Contains("Goods"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Goods).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Goods).ToList();
                }
            }
            else if (sortPath.Contains("Gifts"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Gifts).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Gifts).ToList();
                }
            }
            else if (sortPath.Contains("State"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.State).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.State).ToList();
                }
            }
            else if (sortPath.Contains("DeliveryCompany"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.DeliveryCompany).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.DeliveryCompany).ToList();
                }
            }
            else if (sortPath.Contains("DeliveryNumber"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.DeliveryNumber).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.DeliveryNumber).ToList();
                }
            }
            else if (sortPath.Contains("SenderName"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.SenderName).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.SenderName).ToList();
                }
            }
            else if (sortPath.Contains("SenderPhone"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.SenderPhone).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.SenderPhone).ToList();
                }
            }
            else if (sortPath.Contains("ReceiverName"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Source.ReceiverName).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Source.ReceiverName).ToList();
                }
            }
            else if (sortPath.Contains("ReceiverPhone"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Source.ReceiverPhone).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Source.ReceiverPhone).ToList();
                }
            }
            else if (sortPath.Contains("ReceiverMobile"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Source.ReceiverMobile).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Source.ReceiverMobile).ToList();
                }
            }
            else if (sortPath.Contains("ReceiverAddress"))
            {
                if (sortType == ListSortDirection.Ascending)
                {
                    newVms = vms.OrderBy(obj => obj.Source.ReceiverAddress).ToList();
                }
                else
                {
                    newVms = vms.OrderByDescending(obj => obj.Source.ReceiverAddress).ToList();
                }
            }
            else if (sortPath.Contains("DoorNumber"))
            {
                vms.Sort();
                vms.Sort();
                newVms = vms;
            }
            else
            {
                MessageBox.Show("当前排序方式不支持,请联系添加");
            }
            pageVM.OrderViewModels = null;
            pageVM.OrderViewModels = newVms;
            col.SortDirection = sortType;
        }

        private void miSelectPre_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MenuItem mi = sender as MenuItem;
                var datas = mi.DataContext as PrintOrderPageViewModel;
                if (datas == null)
                {
                    throw new Exception("没有任何数据");
                }
                var dg = ((ContextMenu)mi.Parent).PlacementTarget as DataGrid;
                var cells = dg.SelectedCells;
                if (cells.Count < 1)
                {
                    return;
                }

                var item = cells[0].Item as PrintOrderViewModel;
                if (item == null)
                {
                    throw new Exception("数据对象不正确");
                }

                int index = datas.OrderViewModels.IndexOf(item);

                for (int i = 0; i < datas.OrderViewModels.Count; i++)
                {
                    datas.OrderViewModels[i].IsChecked = i <= index ? true : false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void miSelectForward_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MenuItem mi = sender as MenuItem;
                var datas = mi.DataContext as PrintOrderPageViewModel;
                if (datas == null)
                {
                    throw new Exception("没有任何数据");
                }
                var dg = ((ContextMenu)mi.Parent).PlacementTarget as DataGrid;
                var cells = dg.SelectedCells;
                if (cells.Count < 1)
                {
                    return;
                }

                var item = cells[0].Item as PrintOrderViewModel;
                if (item == null)
                {
                    throw new Exception("数据对象不正确");
                }

                int index = datas.OrderViewModels.IndexOf(item);

                for (int i = 0; i < datas.OrderViewModels.Count; i++)
                {
                    datas.OrderViewModels[i].IsChecked = i >= index ? true : false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void cbbDeliveryTemplates_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                //Grid grid = (sender as ComboBox).Parent as Grid;
                //TextBox tb = grid.FindName("tbDeliveryNumber") as TextBox;
                //var template = (sender as ComboBox).SelectedItem as PrintTemplate;
                //if (template == null)
                //{
                //    tb.Text = "";
                //}
                //else
                //{
                //    tb.Text = LocalConfigService.GetValue(template.Name, "");
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
